package cn.globalph.housekeeper.ui.task

import android.content.DialogInterface
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import cn.globalph.housekeeper.EventObserver
import cn.globalph.housekeeper.R
import cn.globalph.housekeeper.data.retrofit.HttpManager
import cn.globalph.housekeeper.data.source.PreferenceManager
import cn.globalph.housekeeper.data.source.UserInfoPreferenceManager
import cn.globalph.housekeeper.databinding.FragmentTaskBinding
import cn.globalph.housekeeper.ui.BaseFragment
import cn.globalph.housekeeper.ui.dialog.OptionsDialog
import cn.globalph.housekeeper.ui.dialog.StartServerDialog
import cn.globalph.housekeeper.ui.dialog.UserSignDialog
import cn.globalph.housekeeper.utils.MapUtils
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.dialog_download.*
import kotlinx.android.synthetic.main.fragment_task.*

class TaskFragment : BaseFragment(),OptionsDialog.OptionClick,StartServerDialog.StartServerLintener{
    private lateinit var binding:FragmentTaskBinding
    private lateinit var adapter: TaskAdapter

    @Suppress("UNCHECKED_CAST")
    private val viewModel by lazy{
        ViewModelProviders.of(this,object : ViewModelProvider.Factory{
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                val repository = TaskRepository(HttpManager.getInstance())
                return TaskViewModel(repository) as T
            }
        }).get(TaskViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentTaskBinding.inflate(inflater,container,false).apply {
            viewmodel = viewModel
        }
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        binding.lifecycleOwner = this.viewLifecycleOwner
        bar_right.setOnClickListener{
            findNavController().navigate(R.id.action_taskFragment_to_profileTempFragment)
        }

        bar_right2.setOnClickListener {
            var array = arrayOfNulls<String>(viewModel.profiles.value!!.profiles!!.size)
            for(i in 0 until array.size){
                array[i] = viewModel.profiles.value!!.profiles[i].rolename
            }
            showChooseDialog(array)
        }
        setRecyclerView()
        registerObserver()
        viewModel.start()
    }

    private fun setRecyclerView(){
        val viewModel = binding.viewmodel
        if (viewModel != null) {
            adapter = TaskAdapter(viewModel)
            binding.recyclerView.adapter = adapter
            binding.recyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    var pos = parent.getChildAdapterPosition(view)
                    var count = parent.adapter!!.itemCount
                    when (pos) {
                        0 -> outRect.set(dp2px(16f),dp2px(24f),dp2px(16f),0)
                        count-1 -> outRect.set(dp2px(16f),dp2px(24f),dp2px(16f),dp2px(24f))
                        else -> outRect.set(dp2px(16f),dp2px(24f),dp2px(16f),0)
                    }
                }
            })
            binding.refreshLayout.setOnRefreshListener {
                viewModel.getData()
            }

        } else {
        }
    }


    private fun registerObserver(){
        viewModel.showChooseEvent.observe(this,EventObserver{
            showOptionDialog()
        })

        viewModel.tokenEvent.observe(this,EventObserver{
            tokenInvalid()
        })

        viewModel.toastEvent.observe(this,EventObserver{
            TT(it)
        })

        viewModel.dateChangeEvent.observe(this, Observer{
            dataChangeEvent(it)
        })

        viewModel.startDialogEvent.observe(this,EventObserver{
            if(it == DIALOG_CHECK_CARD){
                onWriteCheckCard()
            }else if(it == DIALOG_CUSTOM_SIGN){
                showSignDialog()
            }
        })

        viewModel.refreshOverEven.observe(this,EventObserver{
            binding.refreshLayout.finishRefresh()
        })

        viewModel.itemDataChangeEvent.observe(this,EventObserver{
            Log.i("TaskFragment","dataNotify")
            adapter.notifyDataSetChanged()
        })

        viewModel.saveAlarmEvent.observe(this,EventObserver{
            PreferenceManager.saveAlarmData(context!!,it)
        })
    }

    private fun showOptionDialog(){
        val optionDialog = OptionsDialog()
        optionDialog.setListener(this)
        optionDialog.show(fragmentManager!!,"options")
    }

    private fun showSignDialog(){
        var signDialog = UserSignDialog()
        signDialog.listener = object :UserSignDialog.SignListener{
            override fun onSignClick(bitmap: Bitmap) {
                viewModel.getCustomSignToken(context!!,bitmap!!)
            }
        }
        signDialog.show(fragmentManager!!,"user_sign")
    }

    private fun showStartDialog(){
        val startDialog = StartServerDialog()
        val bundle = Bundle()
        val item = viewModel.currentItem

        item?.let {
            if(!it.actual_start_date.isNullOrEmpty()){
                TT("不能重复开始服务")
                return
            }
            bundle.putString("service_category",it.service_category)
            bundle.putString("name",it.name)
            bundle.putString("actual_start_date",it.actual_start_date)
            bundle.putString("date",viewModel.getDate())
        }
        startDialog.arguments = bundle
        startDialog.listener = this
        startDialog.show(fragmentManager!!,"start_server")
    }

    override fun onGuideClick() {
        val task = viewModel.currentItem
        task?.let {
            MapUtils.showPoint(context,it.lng,it.lat,it.address,"")
        }

    }

    override fun onStartServerClick() {
        showStartDialog()
    }

    override fun onCustomSign() {
        viewModel.checkSignDialogShow()
    }

    override fun onWriteServerLog() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onWriteCheckCard() {
        if(viewModel.currentItem!!.actual_start_date.isNullOrEmpty()){
            TT("请先开始服务!")
            return
        }
        val bundle = Bundle()
        bundle.putString("id",viewModel.currentItem!!.id)
        bundle.putString("attentions",viewModel.currentItem!!.attentions)
        findNavController().navigate(R.id.action_taskFragment_to_checkCardFragment,bundle)
    }

    override fun onStartClick() {
        viewModel.startService(context!!)
    }


    private fun showChooseDialog(array: Array<String?>){
        AlertDialog.Builder(context!!)
            .setTitle(R.string.switch_role)
            .setItems(array
            ) { _, i ->
                viewModel.switchRole(i)
            }
            .show()
    }

    private fun dataChangeEvent(it:String){
        when {
            DATA_SHOW == it -> {
                binding.recyclerView.visibility = View.VISIBLE
                binding.emptyImage.visibility = View.GONE
                binding.emptyImage.setBackgroundResource(R.drawable.ic_empty_common)
                binding.emptyTv.visibility = View.GONE
                binding.emptyTv.text = "没有发现排班~"
                binding.retryBtn.visibility = View.GONE
            }
            DATA_EMPTY == it -> {
                binding.recyclerView.visibility = View.GONE
                binding.emptyImage.visibility = View.VISIBLE
                binding.emptyImage.setBackgroundResource(R.drawable.ic_empty_common)
                binding.emptyTv.visibility = View.VISIBLE
                binding.emptyTv.text = "没有发现排班~"
                binding.retryBtn.visibility = View.GONE
            }
            else -> {
                binding.recyclerView.visibility = View.GONE
                binding.emptyImage.visibility = View.VISIBLE
                binding.emptyImage.setBackgroundResource(R.drawable.ic_error_network)
                binding.emptyTv.visibility = View.VISIBLE
                binding.emptyTv.text = "网络异常~"
                binding.retryBtn.visibility = View.VISIBLE
            }
        }
    }
}